package me.yangteng.zhihudaily.component;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/**
 * Created by MorenYang on 2017/12/18.
 */

public class ScrollListenerView extends ScrollView {
  private boolean isScrollToTop = true;
  private boolean isScrollToBottom = false;

  public ScrollListenerView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
  }

  @Override
  protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
    super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    if (scrollY <= 0) {
      isScrollToTop = clampedY;
      isScrollToBottom = false;
    } else {
      isScrollToTop = false;
      isScrollToBottom = clampedY;
    }
    notifyScrollChangeListeners();
  }

  @Override
  protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    // API > 9 使用onOverScrolled
  }

  public interface OnScrollListener {
    void onScrollToTop();

    void onScrollToBottom();
  }

  private OnScrollListener onScrollListener;


  public void setOnScrollListener(OnScrollListener onScrollListener) {
    this.onScrollListener = onScrollListener;
  }

  public boolean isScrollToTop() {
    return isScrollToTop;
  }

  public boolean isScrollToBottom() {
    return isScrollToBottom;
  }

  private void notifyScrollChangeListeners() {
    // 这里一定要用if elseif 否则会出一些奇奇怪股的bug
    if (isScrollToTop) {
      if (onScrollListener != null) {
        onScrollListener.onScrollToTop();
      }
    } else if (isScrollToBottom) {
      if (onScrollListener != null) {
        onScrollListener.onScrollToBottom();
      }
    }
  }
}
